from Pages.HotelRegister import HotelRegisterPage
from Tools.mysqlControl import use_mysql
import time
import allure


class RegisterAction(HotelRegisterPage):

    # 进行注册
    def action_register(self, user, name, password, phone, gender, is_check_sql):
        gender_id = ''
        self.set_ipt_user(user)
        self.set_ipt_name(name)
        self.set_ipt_password(password)
        self.set_ipt_phone(phone)
        self.create_gender_select()
        self.set_gender(gender)
        self.commit_register()
        if is_check_sql != '-1':
            data = self.select_sql(user=user)
            allure.attach(str(data), 'sql_data')
            assert data[0] == user
            assert data[1] == name
            assert data[2] == password
            assert data[3] == phone
            if gender == '男':
                gender_id = '0'
            elif gender == '女':
                gender_id = '1'
            assert data[4] == gender_id

    # 查询数据库，验证账号是否创建
    @allure.step('验证数据库中是否已创建账号')
    def select_sql(self, user):
        time.sleep(1)
        use_mq = use_mysql()
        # 获取游标
        cursor = next(use_mq)
        sql = 'SELECT user,userName,password,userPhone,userGender FROM users WHERE user="{0}";'.format(user)
        cursor.execute(sql)
        # 获取第一条数据并返回
        data = cursor.fetchone()
        return data

    # 删除测试账号
    @allure.step('删除测试账号')
    def del_test_user(self, test_users):
        use_mq = use_mysql()
        cursor = next(use_mq)
        sql = 'DELETE FROM users WHERE user="{0}"'.format(test_users[0])
        if len(test_users) >1:
            for i in range(len(test_users)):
                if i+1 < len(test_users):
                    sql = sql + ' OR user="{0}"'.format(test_users[i+1])
        # 记录最终的sql语句
        allure.attach(str(sql), 'sql')
        cursor.execute(sql)
        # 验证被删除的条目数量
        allure.attach(str(cursor.rowcount), 'del_nums')

